package com.blb.thread.homework;

/**
 * 用三个线程计算1~100000的和
 * ​	  A线程计算1到30000
 * ​	  B线程计算30001到60000
 * ​	  C线程计算60001到100000
 * ​	  保证ABC顺序执行，最后汇总结果
 */
public class ABCSumDemo {

    private volatile long sum = 0;

    private long calcSum(long min,long max){
        long num = 0;
        for (long i = min; i <= max; i++) {
            num += i;
        }
        return num;
    }

    public static void main(String[] args) {
        ABCSumDemo demo = new ABCSumDemo();
        Thread threadA = new Thread(() -> {
            long res = demo.calcSum(1,30000);
            demo.sum += res;
            System.out.println("A执行完毕");
        });
        Thread threadB = new Thread(() -> {
            threadA.start();
            try {
                threadA.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            long res = demo.calcSum(30001,60000);
            demo.sum += res;
            System.out.println("B执行完毕");
        });
        Thread threadC = new Thread(() -> {
            threadB.start();
            try {
                threadB.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            long res = demo.calcSum(60001,100000);
            demo.sum += res;
            System.out.println("C执行完毕");
        });
        threadC.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("最后结果是：" + demo.sum);
    }
}
